/*
 * @Author: XiaoFeng Chen 
 * @Date: 2018-10-23 12:22:06 
 * @Last Modified by: XiaoFeng Chen
 * @Last Modified time: 2018-10-25 12:33:22
 * 绘制静态图
 */
//@ts-check
const TASK = {
  name: '',
  desc: '',
  sdate: '',
  edate: '',
  percentage: 0,
  rate: ''
}
var _oldChongya;
new Vue({
  el: '#app',
  data: function () {
    return {
      year: '',
      month: '',
      login: {
        islogin: true,
        username: '',
        password: '',
      },
      visible: false,
      form: {
        name: '',
        type: '',
        desc: '',
        percentage: 0,
        tasks: []
      },
      isExists: false,
      activeNames: [],

      isupdate: false,
      history: {
        desc: '',
        percentage: 0,
        date: ''
      }
    }
  },
  methods: {
    onLogin() {
      var username = this.login.username.trim(),
        password = this.login.password.trim();
      if (!username || !password || username !== password) {
        this.$alert('用户名或密码错误。', '登录失败', {
          confirmButtonText: '确定'
        });
        return;
      }
      var _this = this;
      axios.get('data/user.json').then(function (res) {
        if (res.data.data.indexOf(username) !== -1) {
          localStorage.setItem('chongya_isLogin', username)
          _this.login.islogin = username;
          
          axios.post('getya', {
            username: _this.login.islogin,
            year: _this.year,
            month: _this.month,
          }).then(res => {
            if (!res.data.code) {
              _this.isExists = true;
              _this.form = res.data;
              _oldChongya = clone(res.data)
            }
          })
        } else {
          _this.$alert('用户名或密码错误。', '登录失败', {
            confirmButtonText: '确定'
          });
        }
      });
    },
    onSubmit() {
      var _this = this;
      axios.post('addya', {
        username: _this.login.islogin,
        year: _this.year,
        month: _this.month,
        target: _this.form
      }).then(res => {
        _this.isExists = true;
        _this.visible = false;
      })
    },
    onEdit() {
      this.visible = true;
    },
    onTaskDelete(item) {
      console.log(item, this.form.tasks.indexOf(item))
      var _this = this;
      _this.$alert('刪除將無法還原，是否繼續操作？', '冲鸭警告', {
        confirmButtonText: '确定'
      }).then(() => {
        var index = this.form.tasks.indexOf(item);
        _this.form.tasks.splice(index, 1)
        _oldChongya.tasks.splice(index, 1)
      });
    },
    onTaskAdd() {
      this.form.tasks.push(Object.assign({}, TASK))
    },
    onDemo() {
      var _this = this;
      this.$alert('查看demo将会覆盖表單，是否继续？', '冲鸭警告', {
        confirmButtonText: '确定'
      }).then(() => {
        axios.get('data/example.json').then(function (res) {
          console.log(res)
          _oldChongya = clone(res.data)
          _this.form = res.data;
        })
      });
    },
    onItemProcessChange(item) {
      this._indexChanging = this.form.tasks.indexOf(item);
      this.isupdate = true;
    },
    onUpdate() {
      var tasks = this.form.tasks;
      var item = this.form.tasks[this._indexChanging]
      var percent = tasks.map((t) => {
        return t !== item ? t.rate * t.percentage : 0
      }).reduce((d, cur) => d + cur);

      this.form.percentage = (percent + item.rate * item.percentage) / 100;
      var history = {
        date: new Date(),
        content: this.history.desc,
        percentage: item.percentage - _oldChongya.tasks[this._indexChanging].percentage
      }
      var arr = item.history || [];
      arr.push(history);
      item.history = arr;
      var _this = this;
      axios.post('addya', {
        username: _this.login.islogin,
        year: _this.year,
        month: _this.month,
        target: _this.form
      }).then(res => {
        _oldChongya.tasks[this._indexChanging] = clone(item);
        this.isupdate = false;
      })

    },
    onUpdateCancel() {
      this.isupdate = false;
      this.form.tasks[this._indexChanging].percentage = _oldChongya.tasks[this._indexChanging].percentage
    }
  },
  mounted() {
    //登录检测
    Vue.nextTick(() => {;
      // drawTable(tasks);
      //获取当前的月份
      var today = new Date();
      this.year = today.getFullYear().toString();
      var month = today.getMonth() + 1;
      this.month = (month > 9 ? '' : '0') + month
      if (this.login.islogin = localStorage.getItem('chongya_isLogin')) {
        var _this = this;
        axios.post('getya', {
          username: _this.login.islogin,
          year: _this.year,
          month: _this.month,
        }).then(res => {
          if (!res.data.code) {
            _this.isExists = true;
            _this.form = res.data;
            _oldChongya = clone(res.data)
          }
        })
      }
    })
  }
})

function clone(target) {

  if (typeof target != 'object' || target == null) {
    return target
  };

  if (target instanceof Array) {
    var newArr = [];
    for (var i = 0; i < target.length; i++) {
      newArr.push(clone(target[i]));
    }
    return newArr;
  };

  var newObj = new Object();

  for (var i in target) {
    newObj[i] = clone(target[i]);
  }

  return newObj;
};